//
//  LSFollowNewQuesView.m
//  听说弱点强化训练
//
//  Created by 盛超 on 2018/11/5.
//  Copyright © 2018年 盛超. All rights reserved.
//

#import "LSFollowNewQuesView.h"
#import "LSFollowTestView.h"
#import "LSGetZSDManager.h"
#import "LSSaveZSDManager.h"
#import "DicMainView.h"

@interface LSFollowNewQuesView ()<TYAttributedLabelDelegate,LSFollowTestViewDelegate,DicMainViewDelegate>

@property (nonatomic,strong) TYAttributedLabel *contentLabel;

@property (nonatomic,strong) TYAttributedLabel *zsdcontentLabel;

@property (nonatomic,copy) NSString *content;

@property (nonatomic,strong) LSFollowTestView *testView;

@property (nonatomic,strong) DicMainView *dictView;



/*阅读速度*/
@property (nonatomic,assign) CGFloat readRate;
/*播放速度*/
@property (nonatomic,assign) CGFloat playRate;

@end

@implementation LSFollowNewQuesView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        self.backgroundColor = [UIColor whiteColor];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeReleaseAction) name:@"TimeRelease" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimePauseAction) name:@"TimePause" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TimeResumeAction) name:@"TimeResume" object:nil];
    }
    
    return self;
}

- (void)setModel:(LSModelQues *)model {
    _model = model;
    
    if (self.speedLayer==1) {
        _readRate = LS_System.lowSpeed;
    } else if (self.speedLayer==2) {
        _readRate = LS_System.normalSpeed;
    } else if (self.speedLayer==3) {
        _readRate = LS_System.highSpeed;
    }
    
    [self setupUI];
}

- (void)setupUI {
    
    _content = self.model.ChildList.firstObject.ChildAnswer;
    if ([_content isEqualToString:@""] || _content == nil) {
        _content = self.model.QuesBody;
    }
    
    NSAttributedString * attributedText = [_content dr_changeCharSpace:1.5 LineSpace:5 Font:17];//[_content dr_HtmlStringWithFontSize:17];
    self.contentLabel = [[TYAttributedLabel alloc] initWithFrame:CGRectMake(12,10, kWidth-24, 10)];
    self.contentLabel.delegate = self;
    self.contentLabel.attributedText = attributedText;
    self.contentLabel.numberOfLines = 0;
    self.contentLabel.linesSpacing = 5;
    self.contentLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.contentLabel.font = FONT(17);
    [self.contentLabel sizeToFit];
    if (self.contentLabel.height<80) {
        self.contentLabel.height = 80;
    }
    //self.contentLabel.y = self.center.y-100;
    
    [self addSubview:self.contentLabel];
}

- (TYAttributedLabel *)zsdcontentLabel {
    if (!_zsdcontentLabel) {
        
        NSAttributedString * attributedText = [_content dr_changeCharSpace:1.5 LineSpace:5 Font:17];//[_content dr_HtmlStringWithFontSize:17];
        _zsdcontentLabel = [[TYAttributedLabel alloc] initWithFrame:CGRectMake(12, 10, kWidth-24, 10)];
        _zsdcontentLabel.delegate = self;
        _zsdcontentLabel.attributedText = attributedText;
        _zsdcontentLabel.numberOfLines = 0;
        _zsdcontentLabel.linesSpacing = 5;
        _zsdcontentLabel.lineBreakMode = NSLineBreakByWordWrapping;
        _zsdcontentLabel.font = FONT(17);
        [_zsdcontentLabel sizeToFit];
        [self addSubview:_zsdcontentLabel];
        
    }
    
    return _zsdcontentLabel;
}


- (void)startSource {
    LSFollowTestView *testView = [[LSFollowTestView alloc] init];
    self.testView = testView;
    [self addSubview:testView];
    testView.delegate = self;
    testView.pauseType = self.pasueState;
    testView.from = _from;
    testView.speedLayer = _speedLayer;
    testView.model = _model;
    [testView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(W(120));
        make.centerX.equalTo(self);
        make.bottom.equalTo(self.mas_bottom).offset(W(-40));
    }];
    
    if (_answerState==2) {
        [testView showPlayerVoice];
    } else {
        [testView start];
    }
}

- (void)pauseSource {
    
}

- (void)freeSource {
    
}

- (void)reStartSource:(NSInteger)speedLayer {
    [self.testView reStartSpeedLayer:speedLayer];
}

#pragma mark - LSFollowTestViewDelegate
- (void)LSFollowReadReAnswer {
    NSRange range = NSMakeRange(0, self.contentLabel.attributedText.length);
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithAttributedString:self.contentLabel.attributedText];
    [attr addAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} range:range];
    self.contentLabel.attributedText = attr;
    
    [self.zsdcontentLabel removeFromSuperview];
    self.zsdcontentLabel = nil;
}

- (void)LSFollowReadNext {
    
    //切下一题时，进行释放
    self.testView.alpha = 0;
    [self TimeReleaseAction];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(willEnterNextQues)]) {
        [self.delegate willEnterNextQues];
    }
}

- (void)LSFollowReadTestReslut:(NSDictionary *)reslutDict RefText:(NSString*)refText{
    if (self.delegate && [self.delegate respondsToSelector:@selector(FinishAnswerSenDict:RefText:IsSave:)]) {
        [self.delegate FinishAnswerSenDict:reslutDict RefText:refText IsSave:NO];
    }
}

- (void)LSFollowReadShowZSD:(NSString *)testString {
    NSRange range = NSMakeRange(0, self.contentLabel.attributedText.length);
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithAttributedString:self.contentLabel.attributedText];
    [attr addAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} range:range];
    self.contentLabel.attributedText = attr;
    
    LSGetZSDManager *manager = [[LSGetZSDManager alloc] init];
    manager.requestParam = @{@"Text":testString,
                             @"stageNo":KGetUserDefaults(@"TestLayer")
                             };
    WeakObj(self);
    [MBProgressHUD showClearStyleToView:self.zsdcontentLabel];
    [manager requestWithCompltionSuccess:^(NSArray *zsdArr) {
        
        NSMutableArray *mutlCodeArr = [NSMutableArray array];
        NSMutableArray *mutlNameArr = [NSMutableArray array];
        for (LSModelZSD *zsd in zsdArr) {
            [mutlCodeArr addObject:zsd.ZSDCode];
            [mutlNameArr addObject:zsd.ZSDNameInText];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [selfWeak setupLabel:selfWeak.zsdcontentLabel HightlightlyString:selfWeak.zsdcontentLabel.attributedText.string Words:mutlNameArr Codes:mutlCodeArr];
            [MBProgressHUD hideHUDForView:selfWeak.zsdcontentLabel animated:YES];
        });
        
    } failuer:^(NSString *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"知识点错误");
            [MBProgressHUD hideHUDForView:selfWeak.zsdcontentLabel animated:YES];
        });
    }];
}

- (void)LSFollowReadTest:(LSFollowTestView *)testView RecordingTime:(CGFloat)time TotalTime:(NSInteger)totalTime {
    CGFloat len = (time/totalTime * self.contentLabel.attributedText.string.length);
    if (len >= self.contentLabel.attributedText.string.length) {
        len = self.contentLabel.attributedText.string.length;
    }
    NSRange range = NSMakeRange(0, len);
    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithAttributedString:self.contentLabel.attributedText];
    [attr addAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor]} range:range];
    
    self.contentLabel.attributedText = attr;
}

- (void)LSFollowReadTest:(LSFollowTestView *)testView PauseType:(LSQuesPauseType)pauseType {
    self.pasueState = pauseType;
}

- (void)LSFollowReadShowWrongComplteView {
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(retrunShowComplteView)]) {
        [self.delegate retrunShowComplteView];
    }
}

#pragma mark - //**加载高亮**//
- (void)setupLabel:(TYAttributedLabel*)textLabel HightlightlyString:(NSString*)text Words:(NSArray*)words Codes:(NSArray*)codes{
    NSString *string = text;
    
    NSMutableArray *removeHadArr = [NSMutableArray array];
    [string enumerateSubstringsInRange:NSMakeRange(0, string.length-1) options:NSStringEnumerationByWords usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop) {
        
        if([words containsObject:substring] && ![removeHadArr containsObject:substring]) {
            
            [removeHadArr addObject:substring];
            
            NSInteger index = [words indexOfObject:substring];
            //NSString *linkData = codes[index];
            NSString *linkData = [NSString stringWithFormat:@"%@|%@",codes[index],substring];
            [textLabel addLinkWithLinkData:linkData linkColor:[UIColor orangeColor] underLineStyle:kCTUnderlineStyleSingle range:substringRange];
            //textLabel.linesSpacing = 10;
        }
    }];
    
}


#pragma mark - TYAttributedLabelDelegate
- (void)attributedLabel:(TYAttributedLabel *)attributedLabel textStorageClicked:(id<TYTextStorageProtocol>)textStorage atPoint:(CGPoint)point {
    
    if ([textStorage isKindOfClass:[TYLinkTextStorage class]]) {
        NSString *linkStr = ((TYLinkTextStorage*)textStorage).linkData;
        NSLog(@"%@",linkStr);
        
        _dictView = [[DicMainView alloc] initWithTestType:DictTestType_Word isShowRecord:YES];
        _dictView.delegate = self;
        _dictView.dictUrl = [NSString stringWithFormat:@"%@api/ZXYYTS/W_ZXYYTS_GetCoursewareByCode",KGetUserDefaults(@"SystemIP")];
        _dictView.dictParam = @{
                                @"knowledge":[linkStr componentsSeparatedByString:@"|"].firstObject,
                                @"levelCode":KGetUserDefaults(@"TestLayer"),
                                @"stageNo":KGetUserDefaults(@"TestLayer"),
                                @"schoolId":DR_UserInfo.SchoolID,
                                @"stuId":DR_UserInfo.UserID,
                                };
        
        [_dictView popAnimated:YES];
        [_testView cancelRecordPlay];
        
        LSSaveZSDManager *manager = [[LSSaveZSDManager alloc] init];
        
        NSDictionary *dict = @{@"StageNo":KGetUserDefaults(@"TestLayer"),
                               @"SchoolID":KGetUserDefaults(@"SchoolID"),
                               @"StuID":DR_UserInfo.UserID,
                               @"VocabularyID":[linkStr componentsSeparatedByString:@"|"].firstObject,
                               @"Vocabulary":[linkStr componentsSeparatedByString:@"|"].lastObject,
                               @"IsPassed":@0,
                               @"ReviewPassedCount":@0,
                               @"NeedReviewCount":@3,
                               @"CreateTime":[NSDate date] ,
                               @"UpdateTime":[NSDate date]
                               };
        manager.requestParam = @{
                                 @"stageNo":KGetUserDefaults(@"TestLayer"),
                                 @"schoolId":DR_UserInfo.SchoolID,
                                 @"stuId":DR_UserInfo.UserID,
                                 @"ModelUnfamiliarVocabularyList":@[dict]
                                 };
        
        [manager requestSaveWithCompltionSuccess:^(NSString *string) {
            NSLog(@"保存知识点");
        } failuer:^(NSString *error) {
            
        }];
        
    }
    
}

#pragma mark - DicMainViewDelegate
- (void)colseDicMainView:(UIView *)dictView {
    [dictView removeFromSuperview];
    dictView = nil;
}


#pragma mark - 取消定时器/暂停
- (void)TimeReleaseAction {
    NSLog(@"释放时间");
    [self.testView stop];
}

- (void)TimePauseAction {
    [self.testView pause];
}

- (void)TimeResumeAction {
   [self.testView resume];
}

@end
